<!DOCTYPE html>
<html lang="zh-CN">
<head>
    <meta charset="UTF-8">
    <title>区域管理</title>
    <meta name="renderer" content="webkit">
    <meta http-equiv="X-UA-Compatible" content="IE=edge,chrome=1">
    <meta name="viewport" content="width=device-width, initial-scale=1">
    <!--    <link rel="stylesheet" href="../web/resource/css/allcss/allCss.css" type="text/css">-->
    <style>

    </style>
</head>
<body>
<div class="query-container">
    <div class="form-row">
        <!-- 区域名称 -->
        <div class="form-item">
            <label class="form-label">区域名称：</label>
            <input type="text"
                   class="form-input"
                   placeholder="请输入区域名称">
<!--                   placeholder="请输入角色名称">-->
        </div>

        <!-- 状态选择 -->
        <div class="form-item">
            <label class="form-label">类型：</label>
            <select class="form-input form-select">
                <option value="">全部</option>
                <option value="province">省</option>
                <option value="city">市</option>
                <option value="district">区</option>
            </select>
        </div>
    </div>
    <!-- 操作按钮 -->
    <div class="action-buttons">
        <button class="btn btn-reset">重置</button>
        <button class="btn btn-query">查询</button>
        <button class="btn btn-add">新增</button>
    </div>
</div>
<div class="table-container">
    <table class="data-table">
        <thead class="data-table-thead">
        <tr>
            <th>序号</th>
            <th>区域编码</th>
            <th>区域名称</th>
            <th>区域全称</th>
            <th>区域类型</th>
            <th>操作</th>
        </tr>
        </thead>
        <tbody>
        </tbody>
    </table>
    <!-- 分页 -->
</div>
<div class="pagination">
    <span>共0条</span>
    <select class="data-table-page" >
        <option class="" value="10" selected>10条/页</option>
        <option class="" value="20">20条/页</option>
        <option class="" value="50">50条/页</option>
    </select>
    <div class="page-num">
        <button class="pre-button">＜</button>
        <span>1</span>
        <button class="next-button">＞</button>
    </div>
</div>
<div class="modal-mask" id="modal-mask-add">
    <div class="modal-content">
        <h3 class="modal-title">
            新增区域
            <button class="modal-close-btn">×</button>
        </h3>

        <form class="modal-form" id="modal-form-add">
            <div class="form-item">
                <label>区域编码：</label>
                <input type="text"
                       id="add-adCode"
                       placeholder="请输入区域编码"
                       required>
            </div>
            <div class="form-item">
                <label>类型：</label>
                <select id="add-areaType" required>
                    <option value="province">省</option>
                    <option value="city">市</option>
                    <option value="district">区</option>
                </select>
            </div>
<!--            <div class="form-item" id="parent-area-container" style="display:none;">-->
<!--                <label>上级区域：</label>-->
<!--                <select id="parent-area-select" required></select>-->
<!--            </div>-->
            <!-- 新上级区域选择框 -->
<!--            <select-->
<!--                    id="parent-area-select"-->
<!--                    class="form-select"-->
<!--                    data-level="province"-->
<!--                    required-->
<!--            >-->
<!--                <option value="">请选择上级城市</option>-->
<!--                <option value="110000" selected>北京市</option>-->
<!--                <option value="120000">天津市</option>-->
<!--                <option value="130000">河北省</option>-->
<!--            </select>-->
<!--            <select-->
<!--                    class="form-select cascade-select"-->
<!--                    data-level="city"-->
<!--                    required-->
<!--            >-->
<!--                <option value="">请选择下级区域</option>-->
<!--                <option value="110100">北京城区</option>-->
<!--            </select>-->
            <div class="form-item" id="parent-area-container">
                <label>上级区域：</label>
                <select id="parent-area-select" class="form-select" required></select>
            </div>

            <div class="form-item">
                <label>区域名称：</label>
                <input type="text"
                       id="add-name"
                       placeholder="请输入区域名称"
                       required>
            </div>
            <div class="modal-buttons">
                <button type="button" class="btn-close">关闭</button>
                <button type="submit" class="btn-submit">新增</button>
            </div>
        </form>
    </div>
</div>
<!-- 修改更新模态框 -->
<div class="modal-mask" id="modal-mask-update">
    <div class="modal-content">
        <h3 class="modal-title">
            修改区域 <!-- 修改标题 -->
            <button class="modal-close-btn">×</button>
        </h3>
        <form class="modal-form" id="modal-form-update">
            <div class="form-item">
                <label>区域编码：</label>
                <input type="text"
                       id="update-adCode"
                       placeholder="区域编码"
                       readonly> <!-- 编码不可修改 -->
            </div>
            <div class="form-item">
                <label>类型：</label>
<!--                <select id="update-level" required readonly>-->
<!--                    <option value="province">省</option>-->
<!--                    <option value="city">市</option>-->
<!--                    <option value="district">区</option>-->
<!--                </select>-->
                <input type="text"
                       id="update-level"
                       placeholder="区域编码"
                       readonly> <!-- 编码不可修改 -->
            </div>
            <div class="form-item">
                <label>区域名称：</label>
                <input type="text"
                       id="update-name"
                       placeholder="区域名称"
                       required>
            </div>
            <div class="modal-buttons">
                <button type="button" class="btn-close">关闭</button>
                <button type="submit" class="btn-submit">保存</button>
            </div>
        </form>
    </div>
</div>
<!--<script src="//unpkg.com/layui@2.11.0/dist/layui.js"></script>-->

<script>
    const nextButton = document.querySelector('.next-button')
    const preButton = document.querySelector('.pre-button')
    //渲染
    function renderTable(data) {
        document.querySelector('.pagination span:first-child')
            .textContent = `共${data.data.total}条`;
        const tbody = document.querySelector('.data-table tbody');

        // 更新页码显示
        document.querySelector('.page-num span').textContent = data.data.current;

        if (data.data.current >= data.data.pages){
            nextButton.disabled = true;
            nextButton.style.opacity = "0.5";
        }else {
            nextButton.disabled = false;
            nextButton.style.opacity = "1";
        }

        if (data.data.current <= 1){
            preButton.disabled = true;
            preButton.style.opacity = "0.5";
        }else {
            preButton.disabled = false;
            preButton.style.opacity = "1";
        }

        tbody.innerHTML = ''; // 清空旧数据
        data.data.records.
        slice( // 根据分页参数切割数据
            (data.data.current - 1)
            * data.data.size,
            data.data.current * data.data.size
        ).forEach((item, index) => {
            const tr = document.createElement('tr');

            // 生成表格内容
            tr.innerHTML = `
                <td>${(data.data.current - 1) * data.data.size + index + 1}</td>
                <td>${item.adCode}</td>
                <td>${item.name || ''}</td>
                <td>${item.parentNameLis}</td>
               <td>${item.level === 'province' ? '省' : item.level === 'city' ? '市' : '区'}</td>
                <td>
                    <button class="table-edit-btn">修改</button>
                    <button class="table-delete-btn">删除</button>
                </td>
    `;
            // 绑定操作按钮事件
            const editBtn = tr.querySelector('.table-edit-btn');
            const deleteBtn = tr.querySelector('.table-delete-btn');
            // 修改功能
            editBtn.addEventListener('click', () => updateRole(item));

            // 删除功能
            deleteBtn.addEventListener('click', () => deleteRole(item.adCode));

            tbody.appendChild(tr);
        });
    }
    document.querySelector('.btn-query').addEventListener('click',function (){
        fetchData('query');
    })
    document.querySelector('.pre-button').addEventListener('click',function (){
        fetchData('pre');
    })
    document.querySelector('.next-button').addEventListener('click',function (){
        fetchData('next');
    })
    // 统一请求方法
    async function fetchData(type) {

        let { page, pageSize } = getPaginationParams();
        if (type === 'pre') {
            page = Math.max(1, page - 1)  // 确保页码不小于1
            document.querySelector('.page-num span').textContent = page  // 同步更新页码显示
        }else if (type === 'next'){
            page = Math.max(1, page + 1)  // 确保页码不小于1
            document.querySelector('.page-num span').textContent = page  // 同步更新页码显示
        }
        const queryParams = {
            name: document.querySelector('input[placeholder="请输入区域名称"]').value,
            level: document.querySelector('.form-select').value,
            page: page,
            rows: pageSize
        };

        try {
            const response = await fetch('http://localhost:8080/sys/area/pageList', {
                method: 'POST',
                headers: { 'Content-Type': 'application/json' },
                body: JSON.stringify(queryParams)
            });

            const data = await response.json();
            if (data.status === 0) {
                renderTable(data);
                // console.log(data.data)
            }else  if (data.status === -1) {
                console.error('请求失败:', error);
            }
        } catch (error) {
            console.error('请求失败:', error);
            renderTable({ data: { records: [], total: 0, current: 1, pages: 0 } });
        }
    }
    //重置按钮
    document.querySelector('.btn-reset').addEventListener('click',()=>{
        document.querySelectorAll('.form-input').forEach(input => {
            if (input.type === 'text') input.value = '' // 清空文本输入
            if (input.tagName === 'SELECT') input.value = '' // 重置选择框
        });

    })
    //新增按钮相关
    // 显示弹窗
    document.querySelector('.btn-add').addEventListener('click', () => {
        document.querySelector('#modal-mask-add').style.display = 'flex'
    })
    // 关闭弹窗
    document.querySelectorAll('.modal-close-btn').forEach(btn => {
        btn.addEventListener('click', function() {
            this.closest('.modal-mask').style.display = 'none';
        });
    });

    document.querySelectorAll('.btn-close').forEach(btn => {
        btn.addEventListener('click', function() {
            this.closest('.modal-mask').style.display = 'none';
        });
    });
    // 表单提交处理
    document.querySelector('#modal-form-add').addEventListener('submit', async (e) => {
        e.preventDefault()

        const level = document.querySelector('#add-areaType').value;
        const formData = {
            adCode: document.getElementById('add-adCode').value, // 通过ID获取
            parentCode: level !== 'province'
                ? document.getElementById('parent-area-select').value
                : null,
            name: document.getElementById('add-name').value, // 通过ID获取
            level: level
        }

        try {
            const response = await fetch('http://localhost:8080/sys/area/add', {
                method: 'POST',
                headers: { 'Content-Type': 'application/json' },
                body: JSON.stringify(formData)
            })
            const data = await response.json();
            if(data.status===0) {
                alert("添加成功")
                document.querySelector('.modal-mask').style.display = 'none'
                fetchData('query') // 刷新表格数据
            }
        } catch(err) {
            console.error('提交失败:', err)
        }
    })
    //表格函数
    // 新增以下功能函数
    // async function deleteRole(id) {
    //     if (!confirm('确定要删除该角色吗？')) return;
    //     try {
    //         const res = await fetch(`http://localhost:8080/role/delete/${id}`, {
    //             method: 'GET'
    //         });
    //         const data = await res.json();
    //
    //         if(data.status === 0) {
    //             alert('删除成功');
    //             fetchData('query');
    //         }
    //     } catch(err) {
    //         console.error('删除失败:', err);
    //     }
    // }

    // 修改功能弹窗
    let currentEditHandler = null;
    // 修改功能（需要实现编辑弹窗）
    function updateRole(item) {
        // 打开编辑弹窗
        // table-edit-btn
        // const form = document.getElementById('modal-form-update');
        const modal = document.querySelector('#modal-mask-update'); // 需要创建编辑弹窗结构
        // 关闭旧监听器
        if (currentEditHandler) {
            form.removeEventListener('submit', currentEditHandler);
        }
        // 填充表单数据
        const levelMap = { province: '省', city: '市', district: '区' };
        document.getElementById('update-adCode').value = item.adCode;
        document.getElementById('update-level').value = levelMap[item.level];
        document.getElementById('update-name').value = item.name;

        modal.style.display = 'flex';
    }

        // 绑定提交事件
        // 定义新处理器
        // currentEditHandler = async (e) => {
        //     e.preventDefault();
        //     const formData = {
        //         id: item.id,
        //         roleNm: document.querySelector('#edit-roleNm').value,
        //         explaind: document.querySelector('#edit-explaind').value,
        //     };
        //
        //     try {
        //         const res = await fetch('http://localhost:8080/role/update', {
        //             method: 'POST',
        //             headers: {'Content-Type': 'application/json'},
        //             body: JSON.stringify(formData)
        //         });
        //
        //         const data = await res.json();
        //         if(data.status === 0) {
        //             modal.style.display = 'none';
        //             fetchData('query');
        //         }else if (data.status === -1){
        //             modal.style.display = 'none';
        //         }
        //     } catch(err) {
        //         console.error('更新失败:', err);
        //     }
        // };
        // form.addEventListener('submit', currentEditHandler);
    // 修改提交
    document.querySelector('#modal-form-update').addEventListener('submit', async (e) => {
        e.preventDefault();

        const formData = {
            adCode: document.getElementById('update-adCode').value,
            name: document.getElementById('update-name').value,
            level: document.getElementById('update-level').value
        };

        try {
            const res = await fetch('http://localhost:8080/sys/area/update', {
                method: 'POST',
                headers: { 'Content-Type': 'application/json' },
                body: JSON.stringify(formData)
            });

            if(res.status === 0) {
                alert('修改成功');
                fetchData('query');
            }
        } catch(err) {
            alert('修改失败');
        }
    });

    // 删除功能
    async function deleteRole(adCode) {
        if (!confirm(`确认删除区域 ${adCode} 吗？`)) return;

        try {
            const res = await fetch(`http://localhost:8080/sys/area/delete/${adCode}`, {
                method: 'GET'
            });

            if(res.status === 0) {
                alert('删除成功');
                fetchData('query');
            }
        } catch(err) {
            alert('删除失败');
        }
    }

    // 新增区域类型切换监听
    document.querySelector('#add-areaType').addEventListener('change', async function(e) {
        const level = e.target.value;
        const parentContainer = document.querySelector('#parent-area-container');
        const parentSelect = document.querySelector('#parent-area-select');

        // 清空旧数据
        parentSelect.innerHTML = '<option value="">请选择</option>';

        if (level !== 'province') {
            // 根据所选级别获取上级区域（如选city则请求province）
            const upperLevel = level === 'city' ? 'province' : 'city';
            // try {
                const res = await fetch(`http://localhost:8080/sys/area/getSecondLevelArea/${upperLevel}`);
                const data = await res.json();

                if(data.status === 0) {
                    // 填充选项
                    if (upperLevel ==='province') {
                        data.data.forEach(area => {
                            const option = document.createElement('option');
                            option.value = area.id; // 使用区域ID作为值
                            option.textContent = area.name;
                            parentSelect.appendChild(option);
                        });
                    }
                    // }else {
                    //     data.data.children.forEach(area => {
                    //         const option = document.createElement('option');
                    //         option.value = area.id; // 使用区域ID作为值
                    //         option.textContent = area.name;
                    //         parentSelect.appendChild(option);
                    //     });
                    // }

                    parentContainer.style.display = 'block';
                }
            // } catch(err) {
            //     console.error('加载上级区域失败:', err);
            // }
        } else {
            parentContainer.style.display = 'none';
        }
    });



</script>
</body>
</html>